<?php
/**
 * 提现记录
 */

namespace app\admin\model;


use app\common\model\Model;
use think\Db;
use think\Exception;

use app\api\model\User;
use app\api\model\PointsRecord;
class Withdraw extends  Model
{
    const TABLE_NAME = 'withdraw_record';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_1;

    protected $name = self::TABLE_NAME;

    public static function getRecordQuery($user_id=null,$record_account='',$status=0)
    {
        $query = self::commonQuery(self::TABLE_NAME);

        if(is_numeric($user_id))
        {
            $query->where(['record_user_id'=>$user_id]);
        }else if(is_array($user_id))
        {
            $query->where(['record_user_id'=>['in',$user_id]]);
        }
        if($record_account)
        {
            $query->where(['record_account'=>['like','%'.$record_account.'%']]);
        }
        if($status > 0)
        {
            $query->where(['record_status'=>$status]);
        }
         return $query->order('record_time desc');
    }

    public static function handleRecordInfo($info)
    {
        $info['user_name']=UserModel::getUserName($info['record_user_id']);
        $info['record_time']=date('Y-m-d H:i:s',$info['record_time']);
        return $info;
    }
    public static function getRecordStatusForUpdate($record_id)
    {
        $sql ="select record_user_id,record_amount,record_status from withdraw_record where record_id = $record_id for update";

        $res = self::query($sql);


        return empty($res)?[]:$res[0];
    }
    //处理完成
    public static function updateRecordCompleted($record_id)
    {
       return self::commonQuery(self::TABLE_NAME)
           ->where(['record_id'=>$record_id])
           ->setField('record_status',2);
        
    }
    //驳回 提现请求
    public static function refundRecord($record_id,$info)
    {
        self::commonQuery(self::TABLE_NAME)
            ->where(['record_id'=>$record_id])
            ->setField('record_status',3);

        $points = $info['record_amount']  * \app\api\model\Withdraw::POINTS_RATE;

        User::incrUserPoints($info['record_user_id'],$points);
        PointsRecord::addRecord($info['record_user_id'],PointsRecord::POINTS_WITHDRAW_REFUND,$record_id,$points);
    }
}